package com.sjb.thread;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 有点儿意思
 * @Description:
 */
public class ThreadLocalExample {

    /**
     * 使用static修饰threadLocal变量
     */
    private static ThreadLocal<Integer> threadLocalValue =  ThreadLocal.withInitial(() -> 0);

    public void increment(){
        threadLocalValue.set(threadLocalValue.get() + 1);
    }

    public int getValue(){
        return threadLocalValue.get();
    }

    public static void main(String[] args) {
        ThreadLocalExample example1 = new ThreadLocalExample();
        ThreadLocalExample example2 = new ThreadLocalExample();

        Runnable task = () ->{
            for (int i = 0; i < 5; i++) {
                example1.increment();
                example2.increment();
                System.out.println(Thread.currentThread().getName() + "- example1 value: " + example1.getValue());
                System.out.println(Thread.currentThread().getName() + "- example2 value: " + example2.getValue());
            }
        };
        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        thread1.start();
        thread2.start();
    }

}
